'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }

  // 注册
  async sigin() {
    const { ctx } = this
    let { username, password } = ctx.request.body
    const post = await this.app.mysql.get('user', { username });
    if (post) {
      ctx.body = {
        code: 500,
        msg: '账号已存在'
      }
    } else {
      const result = await this.app.mysql.insert('user', { username, password })
      if (result.affectedRows === 1) {
        ctx.body = {
          code: 200,
          msg: '注册成功'
        }
      } else {
        ctx.body = {
          code: 500,
          msg: '注册失败'
        }
      }
    }
  }

  // 登录
  async login() {
    const { ctx } = this
    let { username, password } = ctx.request.body
    let res = await this.app.mysql.get('user', { username, password })
    if (res) {
      ctx.body = {
        code: 200,
        msg: '登录成功'
      }
    } else {
      ctx.body = {
        code: 500,
        msg: '账号密码错误'
      }
    }
  }

  // 修改密码
  async editPassword() {
    const { ctx } = this
    const { username, password, newpassword } = ctx.request.body
    const res = await this.app.mysql.get('user', { username, password })
    if (res) {
      const row = {
        id: res.id,
        password: newpassword
      }
      const result = await this.app.mysql.update('user', row)
      if (result.affectedRows === 1) {
        ctx.body = {
          code: 200,
          msg: '修改成功'
        }
      } else {
        ctx.body = {
          code: 500,
          msg: '账号密码错误'
        }
      }
    } else {
      ctx.body = {
        code: 500,
        msg: '修改失败'
      }
    }
  }

  // 获取数据
  async getList(){
    const {ctx}=this
    const list = await this.app.mysql.select('carlist');
    console.log(list)
    if(list){
      ctx.body={
        code:200,
        list
      }
    }
  }
}

module.exports = HomeController;
